package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.EmpLoyeeMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.IEmployeeService;
import com.itheima.reggie.service.ISetmealDishService;
import com.itheima.reggie.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 员工业务层实现
 *
 * @author panda
 * @since 2022/12/25 2:16
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements ISetmealService {
    @Autowired
    private ISetmealDishService setmealDishService;

    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //1,将基本的套餐信息保存到setmeal表中
        this.save(setmealDto);
        //2,将显示层setmealDto中的套餐菜品信息,存到关系表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //3,需要将刚刚保存金setmeal中的 setmealId加入到setmealdish表中
        //所以要进行for循环
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }

        setmealDishService.saveBatch(setmealDishes);
    }
    //涉及两个表的操作,需要添加事务管理
    @Transactional
    @Override
    public void deleteWithSetmealDish(List<Long> ids) {
        //1,先删除setmeal套餐表中的内容
        //delete from setmeal where id in (1609932923392294913,1609933075024773121);
        //先根据ids查询出对应的setmeal
        //判断count是否大于0,大于0,说明套餐正在售卖
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖,不可以删除");
        }
        this.removeByIds(ids);
        //2,删除关系表setmeal_dish表中的内容
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(lambdaQueryWrapper);

    }
}